using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Microsoft.EPM.TSAutoStatus
{
    public partial class MainForm : Form
    {
        private const string CONN_STR = "Data Source={0};Initial Catalog={1};Integrated Security=True";

        private static string startTime = "";
        private static string processingDuration = "";

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            UpdateStatus status = new UpdateStatus(txtURL.Text);
            status.LogFileEveryHour = true;
            status.LoggingEnabled = true;
            status.LoggingFolder = Application.ExecutablePath;
            status.LoggingPrefix = "Test";
            status.HostName = txtHostName.Text;

            startTime = txtStart.Text;
            processingDuration = txtProcDur.Text;

            try
            {
                lbStatus.Items.Clear();

                if (!ReadyToProcess())
                {
                    lbStatus.Items.Add("Not within processing window.  Start Time=" + startTime + ", Processing Duration=" + processingDuration);
                    return;
                }

                Cursor = Cursors.WaitCursor;

                string conn_str = string.Format(CONN_STR, txtDBServer.Text, txtDBName.Text);
                using (SqlConnection cn = new SqlConnection(conn_str))
                {
                    cn.Open();
                    DataSet ds = RetrieveTimesheets(cn);

                    lbStatus.Items.Add("Processing...");
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        lbStatus.Items.Add("siteGuid=" + row["siteGuid"].ToString() + ", tsGuid=" + row["tsGuid"].ToString());
                        status.ProcessTimesheet((Guid)row["siteGuid"], (Guid)row["tsGuid"], row["lcid"].ToString(), row["userName"].ToString(), true, txtSSPName.Text);
                        lbStatus.Items.Add("Update status on row " + row["ID"].ToString());
                        UpdateStatus(cn, (int)row["ID"]);
                    }
                    lbStatus.Items.Add("Processing complete.");
                    status.FlushLog();
                }
            }
            catch (Exception ex)
            {
                lbStatus.Items.Add(ex.Message);
            }
            finally
            {
                Cursor = Cursors.Default;
            }
        }

        private bool ReadyToProcess()
        {
            // If the processing window is defined, check if currently in that windows.
            int duration;
            DateTime start;
            DateTime end;
            DateTime now = DateTime.Now;
            if (startTime.Length > 0)
            {
                try
                {
                    start = Convert.ToDateTime(startTime);
                    duration = Convert.ToInt32(processingDuration);
                    end = start.AddHours(duration);
                }
                catch (Exception)
                {
                    return false;
                }

                return (now >= start && (now <= end || duration == 0));
            }
            return true;
        }

        private DataSet RetrieveTimesheets(SqlConnection cn)
        {
            try
            {
                DataSet ds = new DataSet();
                SqlCommand cmdRetrieve = new SqlCommand("tsGetUnprocessedTimesheets", cn);
                cmdRetrieve.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter da = new SqlDataAdapter(cmdRetrieve);
                da.Fill(ds);
                return ds;
            }
            catch (Exception ex)
            {
                lbStatus.Items.Add(ex.Message);
                return null;
            }
        }

        private void UpdateStatus(SqlConnection cn, int ID)
        {
            try
            {
                SqlCommand cmdUpdate = new SqlCommand("tsSetTimesheetProcessed", cn);
                cmdUpdate.CommandType = CommandType.StoredProcedure;
                SqlParameter parm = new SqlParameter("ID", SqlDbType.Int, 4);
                parm.Value = ID;
                cmdUpdate.Parameters.Add(parm);
                cmdUpdate.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                lbStatus.Items.Add(ex.Message);
            }
        }

        private void txtURL_TextChanged(object sender, EventArgs e)
        {

        }
    }
}